<template>
  <t-skeleton :loading="loading">
    <div style="margin-bottom: var(--td-comp-margin-s)">
      <t-button
        v-if="plane.result !== 2&&plane.result !==1"
        v-permission="['system:order-designer:save-design-info']"
        @click="
          handleOpenDialog('create', {
            orderId: orderDetails.id,
            logType: 'plane',
            otherFileUrl: [],
            remark: plane.remark,
          })
        "
      >
        上传方案
      </t-button>
      <t-button @click="handleOpenSheet">编辑预算</t-button>
    </div>
    <t-alert v-if="plane.remark || plane.result !== null" style="margin-bottom: var(--td-comp-margin-s)">
      <span  v-if="plane.remark">备注：{{ plane.remark }}</span>
      <span v-if="plane.result !== null" style="margin-left: var(--td-comp-margin-s)"
        ><t-tag :theme="getTagThemeAndLabel(plane.result - 1).theme">{{
          getTagThemeAndLabel(plane.result - 1).label
        }}</t-tag>
      </span>
    </t-alert>
    <div class="content" v-if="plane.fileUrls.length>0">
      <t-space direction="vertical" style="width: 100%">
        <t-collapse expand-mutex @change="handlePanelChange">
          <t-collapse-panel
            v-for="(file, index) in plane.fileUrls"
            :key="index"
            :value="index.toString()"
            :header="getListItemMeta(index, file.createTime)"
          >
            <!-- <t-space direction="vertical" size="large" style="width: 100%">
              <t-list :split="true">
                <t-list-item v-for="(file2, index2) in file.fileUrl" :key="index2">
                  <t-list-item-meta :image="file2.url" :title="file2.name" />
                  <template #action>
                    <t-button variant="text" shape="square" @click="downloadFile(file2.url)">
                      <download-icon />
                    </t-button>
                  </template>
                </t-list-item>
              </t-list>
            </t-space> -->
            <div class="file-container">
              <template v-for="(file2, index) in file.fileUrl" :key="index">
                <file-preview :file="file2" />
              </template>
            </div>
          </t-collapse-panel>
        </t-collapse>
      </t-space>
    </div>
    <!-- 空 -->
    <t-empty v-if="!(plane.remark||plane.result !== null)" style="margin: 100px"></t-empty>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData }"
      :api-map="{ create: createDesignInfo }"
      header="上传方案"
      width="700px"
      :on-before-save-data="handleDialogSaveData"
      @request-success="handleDialogRequestSuccess"
    >
      <!-- 居中 -->
      <t-form-item label="方案文件">
        <upload2 v-model:files="formData.otherFileUrl" />
        <!-- <upload v-model:files="formData.otherFileUrl" /> -->
      </t-form-item>
      <t-form-item label="预算文件">
        <t-button @click="visibleBudget=true;customDialogRef.visible=false">导入预算</t-button>
      </t-form-item>
      <t-form-item label="备注" name="remark" :rules="[{ required: true, message: '请输入备注' }]">
        <t-textarea v-model:value="formData.remark" placeholder="请输入备注" />
      </t-form-item>
    </custom-dialog>
    <!-- 选择预算模板 -->
    <budget-model 
      v-model:visible="visibleBudget"
      @save="handleSaveBudget"
    />
    <t-dialog v-model:visible="visible" attach="body" header="预算模板" :confirm-btn="null" mode="full-screen">
      <!-- <t-card :bordered="false"> -->
        <t-button @click="visibleBudget=true;" style="margin-left: 24px;">导入预算</t-button>
      <!-- </t-card> -->
      <sub-total 
        ref="subTotalRef" 
        :order-id="orderDetails.id" 
        :designer-order-id="orderDetails.designOrderId" 
        v-model:visible="visible" 
      />
      <sheet 
        ref="sheetRef"
        :order-id="orderDetails.id" 
        :designer-order-id="orderDetails.designOrderId" 
        v-model:visible="visible" 
        @refresh-subtotal="handleRefreshSubtotal" 
      />

    </t-dialog>
  </t-skeleton>
  
  <!-- 粘性审批对话框 -->
  <sticky-approve-dialog ref="stickyApproveDialogRef6" :order-id="orderDetails.id" approve-type="6" />
  <sticky-approve-dialog ref="stickyApproveDialogRef12" :order-id="orderDetails.id" approve-type="12" />
  <!-- 发起人 -->
  <sticky-init-approve-dialog :is-multiple="isMultiple" :style="dialog1Style"  ref="stickyInitApproveDialogRef6" :order-id="orderDetails.orderId || orderDetails.id" approve-type="6" />
  <sticky-init-approve-dialog :is-multiple="isMultiple" :style="dialog2Style" ref="stickyInitApproveDialogRef12" :order-id="orderDetails.orderId || orderDetails.id" approve-type="12" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { DownloadIcon } from 'tdesign-icons-vue-next';
import { CollapseProps, MessagePlugin } from 'tdesign-vue-next';
import { computed, inject, onMounted, reactive, Ref, ref, useTemplateRef } from 'vue';

import { createDesignInfo, getDesignInfoList, importBudgetHistory, importBudgetModel } from '@/api/order/details';
import CustomDialog from '@/components/custom/dialog/index.vue';
import Upload2 from '@/components/upload/index2.vue';
import StickyApproveDialog from '@/pages/approve/components/sticky-approve-dialog .vue';
import StickyInitApproveDialog from '@/pages/approve/components/sticky-init-approve-dialog.vue';
import FilePreview from '@/components/file-preview/index.vue';
import BudgetModel from './BudgetModel.vue';
import SubTotal from './SubTotal.vue';
import Sheet from './Sheet.vue';
// import { useDictionaryStore, useUserStore } from '@/store';

// 用户仓库
// const userStore = useUserStore();
// // 字典仓库
// const dictionaryStore = useDictionaryStore();
// 订单详情
const orderDetails = inject<Ref<Record<string, any>>>('orderDetails');
// 容器类名
// const containerClassName = window.document.getElementsByClassName('view-order-scroll').length
//   ? '.view-order-scroll'
//   : '.tdesign-starter-layout';
// 加载状态
const loading = ref(false);
// 方案信息列表
const planeList = ref([]);
// 方案信息
const plane = reactive({
  remark: '',
  result: null,
  fileUrls: [],
});
// 根据审批状态获取标签样式以及文字
const getTagThemeAndLabel = (result: any) => {
  const map = [
    {
      theme: 'warning',
      label: '待审批',
    },
    {
      theme: 'success',
      label: '审批通过',
    },
    {
      theme: 'danger',
      label: '审批不通过',
    },
    {
      theme: 'danger',
      label: '审批已取消',
    },
  ];

  return result in map ? map[result] : { theme: 'default', label: '未知状态' };
};

// 下载文件
const downloadFile = (url: string) => {
  // 浏览器打开url
  window.open(url);
};
const getListItemMeta = (index: number, uploadTime: string) => {
  return `第${index + 1}上传,上传时间为${dayjs(uploadTime).format('YYYY-MM-DD HH:mm:ss')}`;
};
const handlePanelChange: CollapseProps['onChange'] = (val) => {
  console.log(val);
};
// 处理获取方案信息列表
const handleGetplaneList = () => {
  loading.value = true;
  const params = {
    orderId: orderDetails.value.id,
    logType: 'plane',
  };
  getDesignInfoList(params)
    .then((data) => {
      if (!data) return;
      planeList.value = data.fileUrls;
      plane.remark = data.remark;
      plane.result = data.result;
      plane.fileUrls = data.fileUrls;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      loading.value = false;
    });
};
onMounted(() => {
  handleGetplaneList();
});
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  // 设置初始值

  customDialogRef.value.open(mode, params);
};
// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  let isValid = true;
  let st = '';
  const hasWaitingFiles = params.otherFileUrl.some((item: any) => item.status === 'waiting');
  if (hasWaitingFiles) {
    MessagePlugin.warning('有文件待上传，请点击上传文件');
    return false;
  }
  params.otherFileUrl.forEach((item: any) => {
    if (item.type === '') {
      const fileType = item.url.split('.').pop();
      st += fileType;
    } else {
      st += item.type;
    }

    console.log(st);
  });
  console.log(st);
  // 所有图片格式
  if (st.indexOf('image') === -1) {
    MessagePlugin.warning('请上传思维导图');
    isValid = false;
  }
  if (st.indexOf('dwg') === -1) {
    MessagePlugin.warning('请上传dwg文件');
    isValid = false;
  }
  console.log(st,'st')
  // if (st.indexOf('sheet') === -1&&st.indexOf('excel') === -1) {
  //   MessagePlugin.warning('请上传预算文件');
  //   isValid = false;
  // }
  if (!isValid) {
    return false;
  }

  return params;
};
const visibleBudget = ref(false)
const handleSaveBudget = (saveData:any) => {

  if(saveData.type === '1'){
    const params = {
    modelId:saveData.id,
    orderId:orderDetails.value.id,
    designerOrderId: orderDetails.value.designOrderId
  }
    importBudgetModel(params).then((data) => {
     console.log(data,'data');
     handleOpenSheet()
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      // loading.value = false;
    });
  }
  if(saveData.type === '2'){
    const params = {
      moedlOrderId:saveData.id,
      orderId:orderDetails.value.id,
      designerOrderId: orderDetails.value.designOrderId
    }
    importBudgetHistory(params).then((data) => {
     console.log(data,'data');
     handleOpenSheet()
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      // loading.value = false;
    });
  }

}
// 处理打开预算模板对话框
const handleOpenSheet = () => {
  visible.value = true
  sheetRef.value.initData()
  subTotalRef.value.initData()
}
// 处理对话框请求成功
const handleDialogRequestSuccess = () => {
  handleGetplaneList();
};
// 预算模板对话框
const visible = ref(false)
// 预算模板表格ref
const subTotalRef = useTemplateRef('subTotalRef');
const sheetRef = useTemplateRef('sheetRef');
// 处理刷新预算subtotal表格
const handleRefreshSubtotal = () => {
  subTotalRef.value.refreshTable();
};
const onConfirmAnother = (context) => {
  visibleBudget.value=true
};
interface DialogRef {
  visible: boolean;
  open: () => void;
  close: () => void;
}
// 粘性审批对话框ref
const stickyApproveDialogRef6 = useTemplateRef('stickyApproveDialogRef6');
const stickyApproveDialogRef12 = useTemplateRef('stickyApproveDialogRef12');
const stickyInitApproveDialogRef12 = ref<DialogRef | null>(null);
const stickyInitApproveDialogRef6 = ref<DialogRef | null>(null);

onMounted(() => {
  const { approveType } = orderDetails.value;
  if (approveType === '6')   stickyApproveDialogRef6.value.open();
  if (approveType === '12')  stickyApproveDialogRef12.value.open();
  stickyInitApproveDialogRef6.value.open();
  stickyInitApproveDialogRef12.value.open();
});
// 判断是否同时显示多个对话框
const isMultiple = computed<boolean>(() => {
  console.log(stickyInitApproveDialogRef12.value?.visible,'11');
  console.log(stickyInitApproveDialogRef6.value?.visible,'5');
  
  return stickyInitApproveDialogRef12.value?.visible && stickyInitApproveDialogRef6.value?.visible;
});

// 第一个对话框的样式
const dialog1Style = computed(() => {
  if (isMultiple.value) {
    return { left: '40%' }; // 多个对话框时，第一个对话框靠左
  }
  return {}; // 单个对话框时，样式不变
});

// 第二个对话框的样式
const dialog2Style = computed(() => {
  if (isMultiple.value) {
    return { left: '60%' }; // 多个对话框时，第二个对话框靠右
  }
  return {}; // 单个对话框时，样式不变
});
</script>

<style lang="less" scoped>
.content {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  .anchor {
    width: 150px;
    position: sticky;
    top: 100px;
  }

  .list {
    width: 100%;
  }
}
.file-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin: 12px 0;
}
</style>
